package com.lolineet.publisher.service;

import com.alibaba.fastjson.JSONObject;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.lolineet.publisher.properties.PublishProperties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Auther lolineet
 * @Email tj.zhanghongwei@163.com
 * @Date 2021/8/27 10:54
 * @Description
 */
public class Publisher {
    private SocketIOServer socketIOServer;

    public Publisher(PublishProperties publishProperties){
        com.corundumstudio.socketio.Configuration configuration = new com.corundumstudio.socketio.Configuration();
        configuration.setHostname(publishProperties.getServer());
        configuration.setPort(publishProperties.getPort());
        this.socketIOServer=new SocketIOServer(configuration);
    }

    private static final Logger logger = LoggerFactory.getLogger(Publisher.class);
    private static Map<String, SocketIOClient> clientMap = new ConcurrentHashMap<>();

    @PostConstruct
    private void autoStartup() {
        start();
    }

    @PreDestroy
    private void autoStop() {
        stop();
    }
    public void send(String uid,String event,Object data){
        clientMap.get(uid).sendEvent(event,data);
    }
    public void send(String event,Object data){
        clientMap.entrySet().stream().forEach(item->item.getValue().sendEvent(event,data));
    }
    public void send(String event,Object... data){
        clientMap.entrySet().stream().forEach(item->item.getValue().sendEvent(event,data));
    }


    public void start() {
        System.out.println("cccccccccccccccccccccc");
        socketIOServer.addConnectListener(
                client -> {
                    String uid = getParamByClient(client);
                    if (uid != null) {
                        clientMap.put(uid, client);
                        logger.info("有新的客户端连接 UID:{}", uid);
                    }
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("message", "hello client");
                    client.sendEvent("connect", jsonObject);
                }
        );
        socketIOServer.addDisconnectListener(
                client -> {
                    String uid = getParamByClient(client);
                    if (uid != null) {
                        clientMap.remove(uid);
                        client.disconnect();
                        logger.info("客户端{}断开连接", uid);
                        System.out.println("cccccccccccccccccccccc");
                    }
                    logger.info("一条客户端连接中断");
                }
        );
        socketIOServer.start();
    }

    public void stop() {
        if (socketIOServer != null) {
            socketIOServer.stop();
            socketIOServer = null;
        }
        logger.info("socket.io服务关闭");
    }

    private String getParamByClient(SocketIOClient socketIOClient) {
        Map<String, List<String>> params = socketIOClient.getHandshakeData().getUrlParams();
        List<String> list = params.get("UID");
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }
}
